/**
 * author:Administrator
 * date:2016/2/26
 * desc: shopKeeper command 接口
 */

"use strict";

let Ticket = require('../domain/model_cmd/ticket/Ticket.js');
let TicketRepo = require('../domain/model_cmd/ticket/TicketRepo.js');
let Shopkeeper = require('../domain/model_cmd/shopkeeper/Shopkeeper.js');
let ShopkeeperRepo = require('../domain/model_cmd/shopkeeper/ShopkeeperRepo.js');
let Shop = require('../domain/model_cmd/shop/Shop.js');
let ShopRepo = require('../domain/model_cmd/shop/ShopRepo.js');
let ShopWare = require('../domain/model_cmd/shopWare/ShopWare.js');
let ShopWareRepo = require('../domain/model_cmd/shopWare/ShopWareRepo.js');
let WareRepo = require('../domain/model_cmd/ware/WareRepo.js');

let service = {};
module.exports = service;


/**
 * 使用ticket, 消费者凭ticket id进行消费
 * 注意:使用ticket的主体，现实中是用户，但逻辑上却是 shopkeeper
 * @param keeperId
 * @param shopId
 * @param ticketCode
 */
service.useTicket = function * (keeperId, shopId, ticketCode) {
  let keeper = yield ShopkeeperRepo.find(keeperId);
  if (!keeper) return false;                                          // 无此keeper
  let ticket = yield TicketRepo.findByCode(ticketCode);
  if (!ticket) return false;                                          // 无此ticket
  ticket = Ticket.rebuild(ticket);
  let shop = yield ShopRepo.find(shopId);
  if (!shop)return false;                                             // 无此shop

  // 同一商家
  if (keeper.vendorId != ticket.vendorId) return false;               // keeper的商家与ticket的商家要一致
  if (shop.vendorId != keeper.vendorId) return false;                 // shop的商家与keeper的商家要一致

  // 该shop 可以出售此商品
  // 查询 ware
  let snapshot = yield WareRepo.findSnapshot(ticket.snapshotId);
  //if (!snapshot) return false;                                        // 无此snapshot,数据不一致???
  let wareId = snapshot.wareId;
  let shopWare = yield ShopWareRepo.findByShopIdWareId(shopId, wareId);
  if (!shopWare) return false;                                          // 该店无此商品

  // cmd 部分
  console.log('use this ticket');
  yield ticket.consume(keeperId, shopId);
  return true;
};
